// Package service /*
package service

import (
	"log"
	"strings"

	cf "godocker/common/functions"
)

type nginx struct {
	SName string

	basicDir   []string
	name       string
	version    string
	cpFileList []string
}

func nginxNew() *nginx {
	dir := installDir + "/lib/nginx"
	return &nginx{
		"nginx",
		[]string{
			installDir + "/worker/php",
			dir + "/conf",
			dir + "/log",
		},
		cf.GetEnvVal(installDir+"/.env", "nginxname="),
		cf.GetEnvVal(installDir+"/.env", "nginxv="),
		[]string{"conf.d", "fastcgi_params", "mime.types", "nginx.conf", "scgi_params", "uwsgi_params"},
	}
}

func (n nginx) install() {
	n.mkdir()
	n.dockerPull()
	n.upConfig()
}

func (n nginx) mkdir() {
	for i := 0; i < len(n.basicDir); i++ {
		cf.MakeDir(n.basicDir[i])
	}
}

func (n nginx) dockerPull() {
	cf.ExecShell("docker run --name " + n.name + " -dp 80:80 nginx:" + n.version)

	for i := 0; i < len(n.cpFileList); i++ {
		cf.ExecShell("docker cp " + n.name + ":/etc/nginx/" + n.cpFileList[i] + " " + n.basicDir[1])
	}

	cf.ExecShell("docker stop " + n.name)
	cf.ExecShell("docker rm " + n.name)
}

func (n nginx) upConfig() {
	var (
		conf               []byte
		tmp                string
		phpsrc, newphpsrc  string
		fpmsrc, newfpmsrc  string
		indexsrc, newindex string
		file               string
		phpfpm             string
	)
	phpfpm = cf.GetEnvVal(installDir+"/.env", "fpmname=")

	file = n.basicDir[1] + "/conf.d/default.conf"
	phpsrc = "/usr/share/nginx/html"
	newphpsrc = "/var/www/html"

	indexsrc = "index  index.html index.htm;"
	newindex = "index  index.php index.html index.htm;"

	fpmsrc = "#location ~ \\.php$ {\n" +
		"    #    root           html;\n" +
		"    #    fastcgi_pass   127.0.0.1:9000;\n" +
		"    #    fastcgi_index  index.php;\n" +
		"    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;\n" +
		"    #    include        fastcgi_params;\n" +
		"    #}"
	newfpmsrc = "location ~ \\.php$ {\n" +
		"        root           /var/www/html;\n" +
		"        fastcgi_pass   " + phpfpm + ":9000;\n" +
		"        fastcgi_index  index.php;\n" +
		"        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;\n" +
		"        include        fastcgi_params;\n" +
		"    }"

	conf, err := cf.ReadAll(file)
	if err != nil {
		log.Fatal(err)
	}

	tmp = string(conf)

	tmp = strings.Replace(tmp, phpsrc, newphpsrc, -1)
	tmp = strings.Replace(tmp, fpmsrc, newfpmsrc, -1)
	tmp = strings.Replace(tmp, indexsrc, newindex, -1)

	cf.WriteToFileTrunc(file, tmp)
}
